<template>
  <view style="display: flex; flex-direction: column; height: 100vh">
    <xmInfo
      :projectno="itemContent.projectno"
      :projectname="itemContent.projectname"
    ></xmInfo>
	<view style="flex: 1;  overflow: scroll">
    <wn-calendar
      ref="calendar"
      :data="data"
      :isBorder="true"
      :isLess="false"
      :colors="['#f3a73f', '#2979ff', '#8f939c', '#18bc37', '#e43d33']"
      :isEn="false"
      format="/"
      @change="onchange"
      @choose="onChoose"
    ></wn-calendar>
    <view style="padding: 20px">
      <view
        v-if="objDate.date"
        style="background-color: #fff; padding: 10px; border-radius: 10px"
      >
        <view style="margin-bottom: 20px"> 日期：{{ objDate.date }} </view>
        <view v-if="objDate.data"> 记录：{{ objDate.data.text === 'checkbox-mark' ? '已打卡' : '未打卡' }} </view>
        <view v-if="!objDate.data"> 记录：暂无记录！ </view>
        <!-- 不卡按钮 -->
        <!-- <view style="margin-top: 20px">
          <u-button type="primary" @click="add">补卡</u-button>
        </view> -->
      </view>
    </view>
    <view style="height: 80px" v-if="objDate.date&&!objDate.data&&dkflag"></view>
    <view class="btn-group cu-bar foot" v-if="objDate.date&&!objDate.data&&dkflag">
        <button class="cu-btn bg-green shadow-blur" @click="confirm(objDate.date)">
          打卡
        </button>
      </view>
  </view>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo },
  data() {
    return {
      data: [
      ],	
      objDate: {},
      itemContent: {},
      dkflag: hasPermission('app:btn:daka'),
    };
  },

  onLoad(e) {
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        console.log(this.itemContent);
        // 当前年月
        const ddate = this.objDate.year + "-" + this.objDate.month;
        this.getJournalPmJournalListCardData(ddate);
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }
    // 默认把当前的年月日如2024/4/29日
    this.objDate = {
      show: true,
      date: this.getCurrentDate(),
    }
    // 模拟onclick时间调用
    this.onChoose(this.objDate);

  },
  methods: {

    getJournalPmJournalListCardData(ddate) {
      this.$u.api.zfgs
        .journalPmJournalListCardData({
          projectno: this.itemContent.projectno,
          // ddate: this.objDate.year+'-'+this.objDate.month
          ddate: ddate,
        })
        .then((res) => {

          // 遍历res 赋值给data,只取4个字段,把createDate的格式由2024-04-23 11:38 转换成 2024/4/23
          // 把日期转换为2024/4/23 而不是 2024/04/23 月份小于10 取消前面的0，日期小于10 取消前面的0

          this.data = res.map((item) => {
            return {
              date: this.convertDateFormat(item.ddate),
              // 使用图标<u-icon name="star-fill" color="#ff9900" size="20"></u-icon>
              ctype: item.ctype,
              text: "checkbox-mark",
              type: 1,
            };
          });

          
		//   强制更新响应式
		this.$forceUpdate();
		this.$refs.calendar.refresh();
        });
    },
    convertDateFormat(createDateString) {
      const dateParts = createDateString.split(' ');
      const datePart = dateParts[0].split('-');
      // 把datePart[1] 的月份小于10 取消前面的0
      if (datePart[1] < 10) {
        datePart[1] = datePart[1].slice(1);
      }
      if (datePart[2] < 10) {
        datePart[2] = datePart[2].slice(1);
      }
      const formattedDate = `${datePart[0]}/${datePart[1]}/${datePart[2]}`;
      return formattedDate;
    },
    onChoose(e) {
      this.objDate = e;
      console.log(e, "11111111");
    },
    onchange(e) {
      console.log(e, "onchange");
      const ddate = e.year + "-" + e.month;
      this.getJournalPmJournalListCardData(ddate);
    },
    confirm(date){
      // 获取当前时间，格式为年月日
      const currentDate = this.getCurrentDate();
      console.log(currentDate,date,currentDate === date);
      const params = {}
      if(currentDate === date){
        params.projectno = this.itemContent.projectno;
        params.ddate = this.formatConvertDate(date);
      }else{
        params.projectno = this.itemContent.projectno;
        params.ddate = this.formatConvertDate(date);
        params.ctype = 1;
      }
      this.$u.api.zfgs.journalPmJournalSave(params).then(res => {
        if(res.result == 'true'){
          this.$u.toast(res.message);

          this.getJournalPmJournalListCardData(this.formatConvertDate(date))
          this.$refs.calendar.refresh();
        }else{
          // this.$u.toast(res.message);
		  uni.showModal({
		  	title: '提示',
		  	content: res.message,
		  	showCancel: false,
		  	success: function(res) {}
		  });
        }
      })
    },
    // 把日期2024/4/23 转换成 2024-04-23
    formatConvertDate(dateString) {
      const dateParts = dateString.split('/');
      const year = dateParts[0];
      const month = dateParts[1].length === 1 ? '0' + dateParts[1] : dateParts[1];
      const day = dateParts[2].length === 1 ? '0' + dateParts[2] : dateParts[2];
      return `${year}-${month}-${day}`;
    },
    getCurrentDate() {
      const currentDate = new Date();

      const year = currentDate.getFullYear();
      let month = currentDate.getMonth() + 1; // 注意月份是从0开始的，所以需要加1
      let day = currentDate.getDate();

      // 确保月份和日期都是两位数（不足两位时前面补零）
      month = month.toString();
      day = day.toString();
      const formattedCurrentDate = `${year}/${month}/${day}`;
      return formattedCurrentDate;
    },
    
  },
};
</script>
<style lang="scss" scoped>
.cu-bar {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
}
.day-item {
  height: 60px !important;
}
</style>